<template>
  <div class="params">
    <breadcrumb></breadcrumb>
    <!-- 卡片区域制作开始 -->
    <el-card>
      <!-- 提示信息制作开始 -->
      <el-alert show-icon title="注意：只允许为第三级分类设置相关参数！" type="warning" effect="dark" :closable="false" >
      </el-alert>
      <!-- 选择商品分类的制作开始 -->
       <el-row>
        <el-col :span=8>
          <span>选择商品分类：</span>
          <!-- 级联选择框的制作开始 -->
          <el-cascader v-model="selectcateid" :options="categorylist" :props="categoryprops"  @change="handleChange"></el-cascader>
        </el-col>
      </el-row>
      <!-- 属性表格的制作开始 -->
      <el-tabs v-model="activeName" @tab-click="tabschangeClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isButtonShow" @click="addparams">添加参数</el-button>
            <!-- 动态属性的表格显示 -->
           <el-table :data="ManytableData" style="width: 100%">
             <el-table-column type="expand">
               <template slot-scope="scope">
                 <el-tag :key="i" v-for="(item,i) in scope.row.attr_vals" closable @close="handleClose(i,scope.row)">
                  {{item}}
                 </el-tag>
                 <el-input v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" 
                  @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                 </el-input>
                 <el-button v-else  size="small" @click="showInput(scope.row)" >+ New Tag</el-button>
               </template>
             </el-table-column>
             <el-table-column type="index"></el-table-column>
             <el-table-column label="参数名称" prop="attr_name" ></el-table-column>
             <el-table-column label="操作" >
               <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editparams(scope.row.attr_id)">修改</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteparams(scope.row.attr_id)">删除</el-button>
               </template>
             </el-table-column>
           </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
           <el-button type="primary" :disabled="isButtonShow" @click="addparams">添加参数</el-button>
            <!-- 静态参数的表格显示 -->
           <el-table :data="OnlytableData" style="width: 100%">
             <el-table-column type="expand">
               <template slot-scope="scope">
                 <el-tag :key="i" v-for="(item,i) in scope.row.attr_vals" closable @close="handleClose(i,scope.row)">
                  {{item}}
                 </el-tag>
                 <el-input v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" 
                  @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                 </el-input>
                 <el-button v-else  size="small" @click="showInput(scope.row)" >+ New Tag</el-button>
               </template>
             </el-table-column>
             <el-table-column type="index"></el-table-column>
             <el-table-column label="参数名称" prop="attr_name" ></el-table-column>
             <el-table-column label="操作" >
               <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editparams(scope.row.attr_id)">修改</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteparams(scope.row.attr_id)">删除</el-button>
               </template>
             </el-table-column>
           </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数的制作开始 -->
      <el-dialog :title="'添加'+textTitle" :visible.sync="adddialogVisible" width="50%" @close="addparamsclose">
        <el-form ref="addparamsref" :model="addparamsform" :rules="addparamsrules" label-width="80px">
          <el-form-item label="动态参数" prop="attr_name">
            <el-input v-model="addparamsform.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmadd">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑属性的制作开始 -->
      <el-dialog :title="'修改'+textTitle" :visible.sync="editdialogVisible" width="50%">
        <el-form ref="editparamsref" :model="editparamsform" :rules="editparamsrules" label-width="80px">
          <el-form-item label="动态参数" prop="attr_name">
            <el-input v-model="editparamsform.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="canceledit">取 消</el-button>
        <el-button type="primary" @click="confirmedit">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>

import breadcrumb from "../../component/content/breadcrumb.vue"
import {netrequest} from "../../network/request.js"

export default {
  name:'Params',
  components:{
    breadcrumb
  },
  data(){
    return{
      activeName:"many",
      categorylist:[],
      categoryprops:{
        value:'cat_id',
        label:'cat_name',
        children:'children',
        expandTrigger:'hover'
      },
      selectcateid:[],
      ManytableData:[],
      OnlytableData:[],
      // 添加参数的属性
      adddialogVisible:false,
      addparamsform:{
        attr_name:''
      },
      addparamsrules:{
        attr_name:[
        { required: true, message: '参数名称不能为空', trigger: 'blur' },
            ]
      },
      // 修改参数的属性
      editdialogVisible:false,
      editparamsform:{},
      editparamsrules:{
        attr_name:[
        { required: true, message: '参数名称不能为空', trigger: 'blur' },
            ]
      }
    }
  },
  methods:{
    // 请求分类的数据
    async Getcategory(){
      const {data:res} = await netrequest({method:'get',url:'/categories'})
      // console.log(res);
      this.categorylist = res.data
      console.log(this.categorylist);
    },
    // 当级联选择器发生改变时触发该回调函数
    handleChange(){
      // 因为这个请求需要被多次调用，所以把它单独抽成一个方法Getparamsdata
      // if(this.selectcateid.length !==3){
      //   this.selectcateid = []
      //   return
      // }
      // console.log(this.selectcateid);
      // const {data:res} = await netrequest({method:'get',url:`categories/${this.cateId}/attributes`,params:{sel:this.activeName}})
      // console.log(res);
      // if(this.activeName == 'many'){
      //   this.ManytableData = res.data
      // }else{
      //   this.OnlytableData = res.data
      // }
      this.Getparamsdata()
    },
    // 根据三级商品分类的id和动态静态参数来向服务器发送请求
    async Getparamsdata(){
      // 如果选中的商品分类不是三级分类则为空
      if(this.selectcateid.length !==3){
        this.selectcateid = []
        this.ManytableData = []
        this.OnlytableData = []
        return
      }
      console.log(this.selectcateid);
      const {data:res} = await netrequest({method:'get',url:`categories/${this.cateId}/attributes`,params:{sel:this.activeName}})
      console.log(res);
      if(res.meta.status !== 200){
        return this.$message(res.meta.msg)
      }
      // 遍历每一个分类商品判断他们去除空格之后长度是否为0，如果长度为0，则返回空数组，不为0,则进行下一步将字符串以空格分割为数组
      // 然后如果给所有的添加参数都设置一个共用的value和显示隐藏属性，那么修改其中一个，其他的也都会受到影响，所以在遍历时给每一个
      // 元素都加上各自独立的的属性
     res.data.forEach(item => {
          item.inputVisible = false
          item.inputValue = ''
        if(!item.attr_vals){
          return item.attr_vals = []
        }
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') :[]
      });
      if(this.activeName == 'many'){
        this.ManytableData = res.data
        console.log(this.ManytableData);
      }else{
        this.OnlytableData = res.data
      }
    },
    // 标签页发生改变则重新根据新的参数再次发送请求
    tabschangeClick(){
      this.Getparamsdata()
    },
    // 控制添加对话框的显示和隐藏
    addparams(){
      this.adddialogVisible = !this.adddialogVisible
    },
    // 添加参数信息向服务器发送请求
    confirmadd(){
      this.$refs.addparamsref.validate( async valid=>{
        if(!valid) return
        const {data:res} = await netrequest({method:'post',url: `categories/${this.cateId}/attributes`,data:{attr_name:this.addparamsform.attr_name,attr_sel:this.activeName}})
        if(res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.Getparamsdata()
        this.adddialogVisible = !this.adddialogVisible
      })
     
    }
    ,
    // 添加对话框关闭
    addparamsclose(){
      this.$refs.addparamsref.resetFields()
    }
    ,
    // 控制修改对话框的显示和隐藏
    async editparams(id){
      this.editdialogVisible = !this.editdialogVisible
     const {data:res} = await netrequest({method:'get',url:'categories/'+this.cateId+'/attributes/'+id})
     console.log(res);
     if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
     this.editparamsform = res.data
    },
    // 确认修改向服务器发送请求
    confirmedit(){
      this.$refs.editparamsref.validate(async valid=>{
        if(!valid) return
      const {data :res} = await netrequest({method:'put',url:`categories/${this.cateId}/attributes/${this.editparamsform.attr_id}`,data:this.editparamsform})
      console.log(res);
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.Getparamsdata()
      this.editdialogVisible = !this.editdialogVisible
      })
     
    },
    // 取消修改
    canceledit(){
      this.editdialogVisible = !this.editdialogVisible
      this.$message.error('取消修改请求')
    },
    // 删除参数
    async deleteparams(id){
       const confirmresult =  await this.$confirm.confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error=>{
          error
        })

        if(confirmresult === 'confirm'){
        const {data:res}= await netrequest({method:'delete',url:`categories/${this.cateId}/attributes/${id}`})
          console.log(res);}
          else{
            return this.$message.error('删除操作已取消')
          }
          this.Getparamsdata()
          
    },
    // 展开行效果的点击按钮事件,自动聚焦
    showInput(row){
      row.inputVisible = true
      this.$nextTick(_=> {
        this.$refs.saveTagInput.$refs.input.focus()
        }
        );
    },
    // 控制按钮与文本框之间的显示与隐藏

    // 关闭当前的tag标签，并向服务器发送请求
    handleClose(i,row){
      row.attr_vals.splice(i,1)
      this.Saveparamsdata(row)
    },
    // 当enter按键弹起，或者光标消失时，向服务器发送请求添加参数
     handleInputConfirm(row){
      if(row.inputValue.trim().length == 0){
        row.inputValue = ''
        row.inputVisible = false
        return
      }
       row.attr_vals.push(row.inputValue)
       this.Saveparamsdata(row)
    },
    // 因为这个请求需要被用到很多次，所以专门将它抽离为一个函数
    async Saveparamsdata(row){
       const {data:res} = await netrequest({method:'put',url:`categories/${this.cateId}/attributes/${row.attr_id}`,
       data:{ 
         attr_name:row.attr_name,
         attr_sel :row.attr_sel,
         attr_vals:row.attr_vals.join(' ')}})
      console.log(res);
      if(res.meta.status !==200) return this.$message.error(res.meta.msg)
      row.inputVisible = false
      row.inputValue= ''
    }
  },
  computed:{
    // 使用计算属性来判断按钮是否可以点击
    isButtonShow(){
      if(this.selectcateid.length !== 3) return true
      return false
    },
    // 要获取到分类的参数，此时要知道分类的id，所以使用计算属性来保存id
    cateId(){
      if(this.selectcateid.length !==3) return
        return this.selectcateid[2]
    },
    // 静态属性和动态参数共用同一对话框，所以使用计算属性
    textTitle(){
      if(this.activeName == 'many'){
        return '动态参数'
      }
      return '静态属性'
    }
  },
  created(){
    // 向服务器请求后台的分类数据
    this.Getcategory()
  }
}
</script>

<style scoped>
.el-row{
  margin: 20px 0;
}
.el-tag{
  margin:5px;
}
.el-input{
  width: 120px;
}

</style>